/**
 * 
 */
package javapop.framework.parser;

import javapop.framework.DefaultParseResult;
import javapop.framework.ParseContext;
import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.Parser;

/**
 * @author Hakim Belhaouari
 *
 */
public class MaybeOrDefault<T> extends Parser<T> {
	protected Parser<T> child;
	protected T defaultValue;
	
	
	public MaybeOrDefault(Parser<T> child, T defaultValue) {
		this.child = child;
		this.defaultValue = defaultValue;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public ParseResult<?> eval(ParseContext<?> ctx, ParseInput input) {
		ParseResult<T> result = child.parse(ctx,input);
		if(result.isError()) {
			if(result.asError().isFatal()) {
				return (ParseResult) result;
			}
			return new DefaultParseResult<T>((Class<T>) defaultValue.getClass(), defaultValue);
		} else {	
			return result;
		}
	}

	@Override
	public String getDescription() {
		StringBuffer buf = new StringBuffer();
		buf.append("(");
		buf.append(child.getDescription());
		buf.append(")?");
		return buf.toString();
	}
	
	@Override
	public boolean isMemoized() {
		return false;
	}

}
